package com.sxx.beautifulcity.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.sxx.beautifulcity.R;
import com.sxx.beautifulcity.adapter.PluckAdapter;
import com.sxx.beautifulcity.database.PluckHelper;
import com.sxx.beautifulcity.dialog.CommonProgressDialog;
import com.sxx.beautifulcity.entity.DeliciousFoodData;
import com.sxx.beautifulcity.entity.PetData;
import com.sxx.beautifulcity.entity.SpecialityData;
import com.sxx.beautifulcity.entity.Tuan_list_Tongyong;
import com.sxx.beautifulcity.entity.greendao.AgritourismDaoEntity;
import com.sxx.beautifulcity.entity.greendao.AroundDaoEntity;
import com.sxx.beautifulcity.entity.greendao.HolidayDaoEntity;
import com.sxx.beautifulcity.entity.greendao.PluckDaoEntity;
import com.sxx.beautifulcity.entity.greendao.VillageDaoEntity;
import com.sxx.beautifulcity.listenerInterface.OnMyItemClickListener;
import com.sxx.beautifulcity.constant.Constant;
import com.sxx.beautifulcity.popmenu.CommonPopMenu;
import com.sxx.beautifulcity.utils.VolleySingleton;
import com.sxx.beautifulcity.view.SwipeRefreshLoadingLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/22.
 * 采摘
 */
public class PluckActivity extends DialogBaseActivity
        implements View.OnClickListener, OnMyItemClickListener, SwipeRefreshLoadingLayout.OnRefreshListener,
        SwipeRefreshLoadingLayout.OnLoadListener {

    private RecyclerView pluck_recyclerView;
    private PluckAdapter adapter;
    private static String TAG = "PluckActivity";
    private TextView titleTv , moreTv;
    private ImageView backIV;
    private PluckHelper helper;
    private SwipeRefreshLoadingLayout loadingLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview_pluck);
        initView();
        helper = new PluckHelper();
        List<PluckDaoEntity> pluckEntities = helper.queryPluckAll();
        if (pluckEntities.size() == 0) {
            requestPluck();
        }else{
            adapter.addData(pluckEntities);
        }

    }

    public void initView() {
        loadingLayout = (SwipeRefreshLoadingLayout) findViewById(R.id.pluckSl);
        loadingLayout.setOnRefreshListener(this);
        loadingLayout.setOnLoadListener(this);

        backIV = (ImageView) findViewById(R.id.backIV);
        backIV.setOnClickListener(this);

        titleTv = (TextView) findViewById(R.id.titleTv);
        titleTv.setText("采摘");

        moreTv = (TextView) findViewById(R.id.moreTv);
        moreTv.setText("");

        VolleySingleton.getInstance().getQueue();
        adapter = new PluckAdapter(this);
        pluck_recyclerView = (RecyclerView) findViewById(R.id.pluck_recyclerView);
        GridLayoutManager manager = new GridLayoutManager(this, 1);
        pluck_recyclerView.setLayoutManager(manager);
        pluck_recyclerView.setAdapter(adapter);
        adapter.setOnMyItemClick(this);
    }

    public void requestPluck() {
        final Dialog dialog = CommonProgressDialog.createLoadingDialog(this, "正在加载中");
        dialog.show();

        String path = Constant.PLUCK_URL;
        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null && response.has("list_data")) {
                            Log.i("lanou" , response + "");
                            try {
                                JSONArray list_data = response.getJSONArray("list_data");
                                Gson gson = new Gson();
                                List<PluckDaoEntity> datas = new ArrayList<PluckDaoEntity>();
                                for (int i = 0; i < list_data.length(); i++) {
                                    String str = list_data.getString(i);
                                    PluckDaoEntity data = gson.fromJson(str, PluckDaoEntity.class);
                                    datas.add(data);
                                }
                                Log.i("lanou" , datas + "");
                                adapter.addData(datas);
                                helper.deletePluckList(datas);
                                helper.savePluckList(datas);
                                dialog.dismiss();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }

            //解决解析后程序乱码问题
            @Override
            protected Response<JSONObject> parseNetworkResponse(
                    NetworkResponse response) {
                try {
                    String jsonString = new String(response.data, "UTF-8");
                    return Response.success(new JSONObject(jsonString),
                            HttpHeaderParser.parseCacheHeaders(response));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                } catch (Exception je) {
                    return Response.error(new ParseError(je));
                }
            }
        };
        VolleySingleton.getInstance().addRequest(request , TAG);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.backIV:
                Intent intent = new Intent(this , MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.left_out, R.anim.right_into);
                break;

        }
    }

    @Override
    public void onMyItemClick(Tuan_list_Tongyong data) {

    }

    @Override
    public void onMyItemClick(AroundDaoEntity data) {

    }


    @Override
    public void onMyItemClick(HolidayDaoEntity data) {

    }

    @Override
    public void onMyItemClick(AgritourismDaoEntity data) {

    }

    @Override
    public void onMyItemClick(PluckDaoEntity data) {

        Intent intent = new Intent(this ,PluckDetailActivity.class);
        intent.putExtra("id" , data.getId());
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.left_out, R.anim.right_into);
    }

    @Override
    public void onMyItemClick(VillageDaoEntity data) {

    }

    @Override
    public void onMyItemClick(SpecialityData data) {

    }

    @Override
    public void onMyItemClick(DeliciousFoodData data) {

    }

    @Override
    public void onMyItemClick(PetData data) {

    }

    @Override
    public void onRefresh() {
        requestPluck();
    }

    int start = 10;
    int end = 20;
    @Override
    public void onLoad() {
        start = start + 10;
        end = end + 10;
        String path = "http://www.365960.com/plus/api/api.php?" +
                "end=20&lid=31&type=list&city=2&sortby=1&siteid=3729&start="+ start + "end=" + end;
        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null && response.has("list_data")) {
                            Log.i("lanou" , response + "");
                            try {
                                JSONArray list_data = response.getJSONArray("list_data");
                                Gson gson = new Gson();
                                List<PluckDaoEntity> datas = new ArrayList<PluckDaoEntity>();
                                for (int i = 0; i < list_data.length(); i++) {
                                    String str = list_data.getString(i);
                                    PluckDaoEntity data = gson.fromJson(str, PluckDaoEntity.class);
                                    datas.add(data);
                                }
                                Log.i("lanou" , datas + "");
                                adapter.addData(datas);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        VolleySingleton.getInstance().addRequest(request , TAG);
    }
}
